package com.party.admin.web.controller.gatherForm;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.party.admin.biz.file.FileBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.gatherForm.GatherProjectOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.common.utils.UUIDUtils;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherFormInfo;
import com.party.core.model.gatherForm.GatherFormOption;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormOptionService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 表单项目
 *
 * @author Administrator
 *
 */

@SuppressWarnings("all")
@Controller
@RequestMapping("gatherForm/project")
public class GatherProjectController {
	@Autowired
	private IGatherProjectService gatherProjectService;
	@Autowired
	private IGatherFormInfoService gatherFormInfoService;
	@Autowired
	private IGatherFormOptionService gatherFormOptionService;
	@Autowired
	private IGatherFormService gatherFormService;
	@Autowired
	private FileBizService fileBizService;
	@Autowired
	private CosBizService cosBizService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;


	Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping("list")
	public ModelAndView list(GatherProject gatherProject, CommonInput commonInput, Page page) throws Exception {
		page.setLimit(20);
		Map<String, Object> params = CommonInput.appendParams(commonInput);
		List<GatherProject> gatherProjects = gatherProjectService.webListPage(gatherProject, params, page);
		List<GatherProjectOutput> outputs = Lists.newArrayList();
		for (GatherProject input : gatherProjects) {
			GatherProjectOutput output = new GatherProjectOutput();
			MyBeanUtils.copyBeanNotNull2Bean(input, output);

            output.setTotalNum(input.getQuantity());

			// 二维码
			String filePath = fileBizService.getUploadCIPath(input.getCreateBy(), "gatherForm");
			String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + input.getId());
			output.setQrCodeUrl(qrCodeUrl);
			outputs.add(output);
		}

		ModelAndView mv = new ModelAndView("gatherForm/projectList");
		mv.addObject("gatherProjects", outputs);
		mv.addObject("project", gatherProject);
		mv.addObject("input", commonInput);
		mv.addObject("page", page);
		return mv;
	}

	@RequestMapping("toForm")
	public ModelAndView toForm(String id) {
		ModelAndView mv = new ModelAndView("gatherForm/projectForm");
		if (StringUtils.isNotEmpty(id)) {
			GatherProject gatherProject = gatherProjectService.get(id);
			if (StringUtils.isNotEmpty(gatherProject.getContent())) {
				String content = StringUtils.unescapeHtml4Video2Iframe(gatherProject.getContent());
				gatherProject.setContent(content);
			}
			mv.addObject("project", gatherProject);
            Map<String, Object> resultMap = gatherProjectBizService.getFormItems(gatherProject.getId(), gatherProject.getQuantity());
            mv.addAllObjects(resultMap);
		}
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = "save", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult save(GatherProject gatherProject, BindingResult result){
		// 数据验证
		if (result.hasErrors()) {
			List<ObjectError> allErros = result.getAllErrors();
			return AjaxResult.error(allErros.get(0).getDefaultMessage());
		}
		try {
			List<String> newFieldIds = Lists.newArrayList();

			if (StringUtils.isNotEmpty(gatherProject.getContent())) {
				String content = StringUtils.escapeHtml4Iframe2Video(gatherProject.getContent().trim());
				gatherProject.setContent(content);
			}
			String projectId = gatherProject.getId();
			String currentId = Strings.isNullOrEmpty(gatherProject.getCreateBy())?RealmUtils.getCurrentUser().getId():gatherProject.getCreateBy();
			if (StringUtils.isEmpty(gatherProject.getShowPicture())) {
				gatherProject.setShowPicture("1");
			}
			if (StringUtils.isNotEmpty(gatherProject.getId())) {
				GatherProject t = gatherProjectService.get(gatherProject.getId());
				MyBeanUtils.copyBeanNotNull2Bean(gatherProject, t);
				gatherProjectService.update(t);
				currentId = t.getCreateBy();
			} else {
				gatherProject.setCreateBy(currentId);
				gatherProject.setUpdateBy(currentId);
				projectId = gatherProjectService.insert(gatherProject);
			}

			if (StringUtils.isNotEmpty(gatherProject.getShowResource()) && gatherProject.getShowResource().equals("1")) {
				GatherForm resourceForm = gatherFormService.findByCategory(new GatherForm(projectId, Constant.FIELD_RESOURCE));
				if (null == resourceForm) {
					resourceForm = new GatherForm();
					resourceForm.setCategory(Constant.FIELD_RESOURCE);
					resourceForm.setTitle("来源");
					resourceForm.setType("input");
					resourceForm.setProjectId(projectId);
					resourceForm.setDescription("请输入来源");
					resourceForm.setRequired("false");
					resourceForm.setSort(-1);
					gatherFormService.insert(resourceForm);
				}
				GatherForm resourceLinkForm = gatherFormService.findByCategory(new GatherForm(projectId, Constant.FIELD_RESOURCELINK));
				if (null == resourceLinkForm) {
					resourceLinkForm = new GatherForm();
					resourceLinkForm.setCategory(Constant.FIELD_RESOURCELINK);
					resourceLinkForm.setTitle("来源链接");
					resourceLinkForm.setType("input");
					resourceLinkForm.setProjectId(projectId);
					resourceLinkForm.setDescription("请输入来源链接");
					resourceLinkForm.setRequired("false");
					resourceLinkForm.setSort(0);
					gatherFormService.insert(resourceLinkForm);
				}

				newFieldIds.add(resourceForm.getId());
				newFieldIds.add(resourceLinkForm.getId());
			}

            gatherProjectBizService.saveFormItems(gatherProject.getItems(), projectId, currentId, newFieldIds);

			try {
				String filePath = fileBizService.getUploadCIPath(currentId, "gatherForm");
				String content = "gather_form/form_info.html?projectId=" + projectId;
				fileBizService.uploadCloudOut(projectId, filePath, content, currentId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return AjaxResult.success();
		} catch (Exception e) {
		    logger.error("保存项目异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error(e.getMessage());
		}
	}


	@ResponseBody
	@RequestMapping(value = "copyOne")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult copyOne( @RequestParam("id") String id) {
		if (id != null && !id.isEmpty()) {//开始进行复制操作

			List<String> newFieldIds = Lists.newArrayList();

			GatherProject gatherProject = gatherProjectService.get(id);//先取得需要复制的project对象
			String currentId = Strings.isNullOrEmpty(gatherProject.getCreateBy()) ? RealmUtils.getCurrentUser().getId() : gatherProject.getCreateBy();
			gatherProject.setCreateBy(currentId);
			gatherProject.setUpdateBy(currentId);
            gatherProject.setId(UUIDUtils.generateRandomUUID());
            gatherProject.setQuantity(0L);//清空收集人数
            gatherProject.setUpdateDate(new Date());//置顶当前project
			try {
                gatherProjectService.insert(gatherProject);//对需要复制的project对象赋值后进行新的对象插入生成
				String newProjectId = gatherProject.getId();

				if (StringUtils.isNotEmpty(gatherProject.getShowResource()) && gatherProject.getShowResource().equals("1")) {
					GatherForm resourceForm = gatherFormService.findByCategory(new GatherForm(newProjectId, Constant.FIELD_RESOURCE));
					if (null == resourceForm) {
						resourceForm = new GatherForm();
						resourceForm.setCategory(Constant.FIELD_RESOURCE);
						resourceForm.setTitle("来源");
						resourceForm.setType("input");
						resourceForm.setProjectId(newProjectId);
						resourceForm.setDescription("请输入来源");
						resourceForm.setRequired("false");
						resourceForm.setSort(-1);
						gatherFormService.insert(resourceForm);
					}
					GatherForm resourceLinkForm = gatherFormService.findByCategory(new GatherForm(newProjectId, Constant.FIELD_RESOURCELINK));
					if (null == resourceLinkForm) {
						resourceLinkForm = new GatherForm();
						resourceLinkForm.setCategory(Constant.FIELD_RESOURCELINK);
						resourceLinkForm.setTitle("来源链接");
						resourceLinkForm.setType("input");
						resourceLinkForm.setProjectId(newProjectId);
						resourceLinkForm.setDescription("请输入来源链接");
						resourceLinkForm.setRequired("false");
						resourceLinkForm.setSort(0);
						gatherFormService.insert(resourceLinkForm);
					}

					newFieldIds.add(resourceForm.getId());
					newFieldIds.add(resourceLinkForm.getId());
				}

				List<GatherForm> gatherFormList = gatherFormService.findByProjectId(id);
                gatherFormList.stream().forEach(form -> {
					GatherFormOption gatherFormOption = new GatherFormOption();
					gatherFormOption.setFieldId(form.getId());
					//加载自定义表单下当前表单项的所有子项目，并进行项目填充
					form.setSubitems(gatherFormOptionService.list(gatherFormOption));
                    form.setId("");
                    form.setProjectId(newProjectId);
                    gatherFormService.insert(form);
                });//对需要复制的project进行表单项插入
				gatherProject.setItems(gatherFormList);

                //对需要复制的project进行其他包括option项的插入生成
				gatherProjectBizService.saveFormItems(gatherProject.getItems(), newProjectId, currentId, newFieldIds);
				String filePath = fileBizService.getUploadCIPath(currentId, "gatherForm");
				String content = "gather_form/form_info.html?projectId=" + newProjectId;
				fileBizService.uploadCloudOut(newProjectId, filePath, content, currentId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return AjaxResult.success("当前项目复制成功");
		}
		return AjaxResult.error("未将projectId传入进来");
	}



    /**
     * 删除项目
     *
     * @param id 项目id
     * @return
     */
	@ResponseBody
	@RequestMapping("delete")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult delete(String id) {
		GatherProject gatherProject = gatherProjectService.get(id);
		if (gatherProject == null) {
			return AjaxResult.error("信息收集项目不存在");
		}
		List<GatherFormInfo> infos = gatherFormInfoService.list(new GatherFormInfo(id));
		if (infos.size() > 0) {
			return AjaxResult.error("已有收集信息，不能删除");
		}
		String uploadPath = fileBizService.getUploadCIPath(gatherProject.getCreateBy(), "gatherForm");
		boolean result = gatherProjectBizService.deleteProjectBiz(null, id, uploadPath);
		if (result) {
			return AjaxResult.success();
		} else {
			return AjaxResult.error("删除失败");
		}
	}

	@ResponseBody
	@RequestMapping("initQrCode")
	public AjaxResult initQrCode() {
		try {
			List<GatherProject> gatherProjects = gatherProjectService.list(new GatherProject());
			for (GatherProject project : gatherProjects) {
				String currentId = project.getCreateBy();
				String filePath = fileBizService.getUploadCIPath(currentId, "gatherForm");
				String path = currentId + "/gatherForm/form/";
				String content = "gather_form/form_info.html?projectId=" + project.getId();
				fileBizService.uploadCloudOut(project.getId(), filePath, path, project.getId(), content, currentId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("二维码初始化失败");
		}
		return AjaxResult.success();
	}

    /**
     * 初始化收集数量
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initQuantity")
    public AjaxResult initQuantity() {
        List<GatherProject> gatherProjects = gatherProjectService.list(new GatherProject());
        for (GatherProject project : gatherProjects) {
            Long quantity = gatherFormInfoService.getCountById(project.getId());
            GatherProject gatherProject = gatherProjectService.get(project.getId());
            gatherProject.setQuantity(quantity == null ? 0 : quantity);
            gatherProjectService.update(gatherProject);
        }
        return AjaxResult.success();
    }

	/**
	 * 校正数量
	 *
	 * @param projectId 项目id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("reviseQuantity")
	public AjaxResult reviseQuantity(String projectId) {
		try {
			GatherProject gatherProject = gatherProjectService.get(projectId);
			Long quantity = gatherFormInfoService.getCountById(gatherProject.getId());
			gatherProject.setQuantity(quantity);
			gatherProject.setUpdateDate(null);
			gatherProjectService.update(gatherProject);
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("信息收集项目校正数量异常", e);
			return AjaxResult.error("校正失败");
		}
	}
}
